
package com.leyca;

import it.gerdavax.android.bluetooth.BluetoothDevice;
import it.gerdavax.android.bluetooth.LocalBluetoothDevice;
import it.gerdavax.android.bluetooth.LocalBluetoothDeviceListener;
import it.gerdavax.android.bluetooth.RemoteBluetoothDevice;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class DescubreDispositivos extends ListActivity {
	private static final String TAG = "DescubrimientoDispositivo";
	protected LocalBluetoothDevice localBluetoothDevice;
	protected static ProgressDialog dialog;
	protected static ProgressDialog dialog2;
	protected Handler handler = new Handler();
	protected ArrayList<String> devices;
	protected AlertDialog deviceInfoDialog;
	
	// Devuelve Intent extra con la MAC
	 public static String EXTRA_DEVICE_ADDRESS = "device_address";

	protected class AdaptadorDispositivo extends BaseAdapter implements LocalBluetoothDeviceListener {

		public int getCount() {
			if (devices != null) {
				return devices.size();
			}
			return 0;
		}

		public Object getItem(int position) {
			return devices.get(position);
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout feedItem = null;

			try {
				if (convertView == null) {
					feedItem = new LinearLayout(DescubreDispositivos.this);
					String inflater = Context.LAYOUT_INFLATER_SERVICE;
					LayoutInflater vi = (LayoutInflater) DescubreDispositivos.this.getSystemService(inflater);
					vi.inflate(R.layout.item, feedItem, true);
				} else {
					feedItem = (LinearLayout) convertView;
				}

				TextView feedTitle = (TextView) feedItem.findViewById(R.id.address);
				TextView deviceNameAndClass = (TextView) feedItem.findViewById(R.id.name);

				String address = devices.get(position);
				String name = "null";
				String deviceClass = "null";
				try {
					name = localBluetoothDevice.getRemoteBluetoothDevice(address).getName();
					
					RemoteBluetoothDevice remoteBluetoothDevice = localBluetoothDevice.getRemoteBluetoothDevice(address);

					switch (remoteBluetoothDevice.getDeviceMajorClass()) {
						case BluetoothDevice.BluetoothClasses.DEVICE_MAJOR_COMPUTER:
							System.out.println("- Esto es una computadora");
							break;
						case BluetoothDevice.BluetoothClasses.DEVICE_MAJOR_PHONE:
							System.out.println("- Esto es un teléfono");
							break;
						case BluetoothDevice.BluetoothClasses.DEVICE_MAJOR_IMAGING:
							System.out.println("- Esto es un dispositivo imaginario");
							break;
						case BluetoothDevice.BluetoothClasses.DEVICE_MAJOR_PERIPHERAL:
							System.out.println("- Esto es un periférico genérico");
							break;
						case BluetoothDevice.BluetoothClasses.DEVICE_MAJOR_AV:
							System.out.println("- Esto es un dispositivo AV");
							break;
						default:
							System.out.println("- Esto es otro");
							break;
					}

					switch (remoteBluetoothDevice.getServiceMajorClass()) {
						case BluetoothDevice.BluetoothClasses.SERVICE_MAJOR_CLASS_POSITION:
							System.out.println("-- Esto es un GPS");
							break;
						case BluetoothDevice.BluetoothClasses.SERVICE_MAJOR_CLASS_INFORMATION:
							System.out.println("-- Esto es una información del dispositivo");
							break;
					}
					
					deviceClass = "" + remoteBluetoothDevice.getDeviceClass();
										

				} catch (Exception e) {
					e.printStackTrace();
					name = "ERROR";
				}

				if (name != null) {
					deviceClass = name + " - " + deviceClass;
				}

				feedTitle.setText(address);
				deviceNameAndClass.setText(name);

			} catch (Exception e) {
			}

			return feedItem;
		}

		public void scanCompleted(ArrayList<String> devs) {
			devices = devs;
			notifyDataSetChanged();
			hideProgressDialog();
		}

		public void scanStarted() {
			showProgressDialog();
		}

		public void disabled() {

		}

		public void enabled() {

		}

		@Override
		public void bluetoothDisabled() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void bluetoothEnabled() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void deviceFound(String deviceAddress) {
			// TODO Auto-generated method stub
			
		}

	}

		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.test);

		AdaptadorDispositivo adaptador = new AdaptadorDispositivo();
		setListAdapter(adaptador);

		try {
			localBluetoothDevice = LocalBluetoothDevice.initLocalDevice(this);

			if (localBluetoothDevice.isEnabled()) {
				Log.d(TAG, "Bluetooth está Activado");
				Toast.makeText(this, "Mi MAC: " + localBluetoothDevice.getAddress(), Toast.LENGTH_LONG).show();
				
				localBluetoothDevice.setListener(adaptador);

				showDialog(DescubreDispositivos.this, R.string.dialog_descubre_dispositivos);

			} else {
				showDialog(DescubreDispositivos.this, R.string.bluetooth_desactivado);
			}
			
		} 
		catch (Exception e) {
		}

		getListView().setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				try {
					//showProgressDialogConectando();
					
					// Obtener la addres MAC del dispositivo seleccionado
					String info = ((TextView) arg1).getText().toString();
					String address = info.substring(info.length() -17 );
					
					// Crear el result Intent e incluir la address MAC
					Intent intent = new Intent();
					intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
										
					// Establece el resultado y finaliza la Activity
					setResult(Activity.RESULT_OK, intent);
					finish();					
					
					 
					} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		localBluetoothDevice.close();
	}

	protected void showProgressDialog() {
		handler.post(new Runnable() {
			public void run() {
				dialog = ProgressDialog.show(DescubreDispositivos.this, "", "Escaneando dispositivos Bluetooth. Porfavor espere...", true);

				System.out.println(dialog);
			}
		});
	}
	protected void showProgressDialogConectando() {
		handler.post(new Runnable() {
			public void run() {
				dialog2 = ProgressDialog.show(DescubreDispositivos.this, "", "Realizando la conexión entre Leica DISTO y su teléfono, Porfavor espere...", true);

				System.out.println(dialog2);
			}
		});
	}
	protected void hideProgressDialog() {
		handler.post(new Runnable() {
			public void run() {
				if (dialog != null) {
					dialog.dismiss();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 0, Menu.NONE, "Escanear").setIcon(android.R.drawable.ic_menu_search);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			try {
				showProgressDialog();
				localBluetoothDevice.scan();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("¿Está seguro que desea Salir?").setCancelable(false).setPositiveButton("Cerrar", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		
		deviceInfoDialog= builder.create();

		return deviceInfoDialog;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		if (dialog == deviceInfoDialog) {
			deviceInfoDialog.setMessage("");
		} else {
			super.onPrepareDialog(id, dialog);
		}
	}
	
	public static void showDialog(Context context, int text) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(text).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}

		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
}
